package com.wzgl.core.controller;

import java.math.BigInteger;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Redis;
import com.wzgl.core.CacheConsts;
import com.wzgl.core.base.JBaseCRUDController;
import com.wzgl.core.config.plugin.QuartzManager;
import com.wzgl.core.interceptor.RequiredUserIdInterceptor;
import com.wzgl.core.model.Tdicinfo;
import com.wzgl.core.model.Tmagic;
import com.wzgl.core.server.QuartService;
import com.wzgl.core.utils.DateUtils;
import com.wzgl.core.utils.StringUtils;
import com.wzgl.core.utils.UuidUtil;
import com.wzgl.core.utils.WZGLUtils;


public class MagicController extends JBaseCRUDController<Tmagic> {
	static QuartService qtservice = QuartService.me;
	
	@Before(RequiredUserIdInterceptor.class)
	public void magic_index() {
		render("magic_list.jsp");
	}
	
	/**
	 * 用户管理 列表数据
	 */
	@Before(RequiredUserIdInterceptor.class)
	public void magic_list(){
		Page<Tmagic> list_page;
//		WebMagicMap mm = WebMagicMap.getIstance();
		try {
			BigInteger page=getParaToBigInteger("page",BigInteger.valueOf(1));
			BigInteger pagesize=getParaToBigInteger("pagesize",BigInteger.valueOf(5));
			String fvalue =  getParaTo("fvalue");
			list_page= Tmagic.dao.paginate(page.intValue(),pagesize.intValue(),fvalue);
			/**
			 * 为后期爬虫放入缓存中,或者代理爬取。
			 */
//			for(Tmagic t : list_page.getList()){
//				if(mm.get(t.getFurl())!= null){
//					Spider s = (Spider) mm.get(t.getFurl());
//					if(s != null && StringUtils.isNotBlank(s.getStatus().toString())){
//						t.setFstats(s.getStatus().toString());
//					}
//				}
//			}
			renderAjaxResult("",0,list_page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderAjaxResultForError(e.getMessage());
		}
	}


	//开启
	@Before(RequiredUserIdInterceptor.class)
	public void magic_work() throws Exception{
		String fid = getPara("fid");
		Tmagic t = Tmagic.dao.findById(fid);
		String fur = t.getFurl();
		if(("").equals(t.getFstats()) || ("1").equals(t.getFstats())){
			renderJson(Ret.fail());
		}else{
			//清除上次爬虫缓存
			String logcachename = CacheConsts.CACHE_LOG_MAGIC_NAME;
			String urlcachename = CacheConsts.CACHE_QUARTZ_NAME;
			String key = logcachename+":"+fur;
			WZGLUtils.del(logcachename, key);
			//记录爬取日志开始时间
			String value = "启动："+DateUtils.now()+"\r";
			WZGLUtils.setCache(logcachename, key, value);
			
			Object obj = WZGLUtils.getCache(urlcachename, t.getFpage());
			t.setFstats("1");  //开启状态
			if(obj != null){
				if(qtservice.update(t)){
					//重新启动调度任务
					//记录到缓存
					String cachename2 = CacheConsts.CACHE_QUARTZ_NAME;
					String name2 = cachename2+":"+t.getFpage();
					String value2 = t.toJson();
					WZGLUtils.setCache(urlcachename, name2, value2);
					QuartzManager.shutdownJobs();
					Thread.sleep(1000);
					new QuartzManager().start();
				}else{
					renderJson(Ret.fail());
				}
			}else{
				if(qtservice.update(t)){
					String urlkey = CacheConsts.CACHE_QUARTZ_NAME+":"+t.getFpage();
					WZGLUtils.setCache(urlcachename, urlkey, t.toJson());
					QuartzManager.addJob(t.getFpage(), t.getFclass(), t.getFcycle());
				}else{
					renderJson(Ret.fail());
				}
			}
		}
		renderJson(Ret.ok());
	}
	
	//暂停爬取
	public void magic_stop() throws Exception{
		String fid = getPara("fid");
		Tmagic t =  Tmagic.dao.findById(fid);
		
		if(t.getFstats() == null || t.getFstats().equals("0") || t.getFstats().equals("2")){
			renderJson(Ret.fail());
		}else{
			Object obj = WZGLUtils.getCache(CacheConsts.CACHE_QUARTZ_NAME, t.getFpage());
			if(obj != null){
				t.setFstats("2");
				//修改数据库    状态为    暂停2
				if(qtservice.update(t)){
					//记录到缓存
					String cachename2 = CacheConsts.CACHE_QUARTZ_NAME;
					String name2 = cachename2+":"+t.getFpage();
					String value2 = t.toJson();
					WZGLUtils.setCache(cachename2, name2, value2);
					//重新启动调度任务
					QuartzManager.shutdownJobs();
					Thread.sleep(1000);
					new QuartzManager().start();
				}else{
					renderJson(Ret.fail());
				}	
			}else{
				renderJson(Ret.fail());
			}
		}
		renderJson(Ret.ok());
	}
	
	//移除
	public void magic_remove() throws Exception{
		String fid = getPara("fid");
		Tmagic t =  Tmagic.dao.findById(fid);
		if(t.getFstats() == null || t.getFstats().equals("0")){
			renderJson(Ret.fail());
		}else{
			Object obj = WZGLUtils.getCache(CacheConsts.CACHE_QUARTZ_NAME, t.getFpage());
			if(obj != null){
				t.setFstats("0");  //移除状态
				if(qtservice.update(t)){
					//清除缓存
					String cachename = CacheConsts.CACHE_QUARTZ_NAME;
					String key = CacheConsts.CACHE_QUARTZ_NAME+":"+t.getFpage();
					WZGLUtils.del(cachename, key);
					//清除此任务  
					QuartzManager.removeJob(t.getFpage());
				}else{
					renderJson(Ret.fail());
				}	
			}else{
				renderJson(Ret.fail());
			}
		}
		renderJson(Ret.ok());
	}
	
	//立即执行
	public void magic_startnow() throws Exception{
		String fid = getPara("fid");
		Tmagic t =  Tmagic.dao.findById(fid);
		String fur = t.getFurl();
		if(t.getFstats() == null){
			renderJson(Ret.fail());
		}else{
			//获取任务调度,不存在则添加新的任务。
			Object obj = WZGLUtils.getCache(CacheConsts.CACHE_QUARTZ_NAME, t.getFpage());
			if(obj == null){
				//增加调度任务
				QuartzManager.addJob(t.getFpage(), t.getFclass(), t.getFcycle());
			}else{
				QuartzManager.addJob(t.getFpage(), t.getFclass(), t.getFcycle());
			}
			//记录启动日志
			String cachename = CacheConsts.CACHE_LOG_MAGIC_NAME;
			String name = cachename+":"+fur;
			String value = "启动："+DateUtils.now()+"\r";
			WZGLUtils.setCache(cachename, name, value);
			if(QuartzManager.runJob(t.getFpage())){				
				//全部记录为移除
				t.setFstats("0");
				if(qtservice.update(t)){
					String cachename2 = CacheConsts.CACHE_QUARTZ_NAME;
					String name2 = cachename2+":"+t.getFpage();
					String value2 = t.toJson();
					WZGLUtils.setCache(cachename2, name2, value2);
					QuartzManager.removeJob(t.getFpage());
				}
			}
		}
		renderJson(Ret.ok());
	}
	
	//获取爬虫日志,爬虫只记录最后一次日志。
	@Before(RequiredUserIdInterceptor.class)
	public void magic_log(){
		String fid = getPara("fid");
		Tmagic t = Tmagic.dao.findById(fid);
		String fur = t.getFurl();
		String cachename = CacheConsts.CACHE_LOG_MAGIC_NAME;
		String key = cachename+":"+fur;
		String log = (String) WZGLUtils.getCache(cachename, key);
		if(StringUtils.isNotBlank(log)){
			setAttr("log", log);
		}else{
			setAttr("log","爬虫日志不存在.");
		}
		render("magic_log.jsp");
	}
	//获取爬虫日志,爬虫只记录最后一次日志。
	@Before(RequiredUserIdInterceptor.class)
	public void magic_grid(){
		String fid = getPara("fid");
		setAttr("fmzgicId", fid);
		render("magic_gird.jsp");
	}
	/***
	 * 爬虫的信息
	 */
	@Before(RequiredUserIdInterceptor.class)
	public void magic_edit(){
		String fid = getPara("fid");
		Tmagic t =null;
		List<Tdicinfo> tdic = Tdicinfo.dao.getTdicBySort(PropKit.use("wzgl_tdinc_conts.txt").get("tdic_wzlx"));
		setAttr("tdic", tdic);
		if(StrKit.notBlank(fid)){
			t = Tmagic.dao.findById(fid);
			setAttr("tmagic", t);
		}
		render("magic_edit.jsp");
	}
	/**
	 * 保存爬虫的信息
	 */
//	@Before(EvictInterceptor.class)
	@Before(RequiredUserIdInterceptor.class)
	public void magicSave(){
		Tmagic t = getModel(Tmagic.class);
		Ret r = new Ret();
		boolean b = false;
		if(StrKit.isBlank(t.getFid())){
			t.setFid(UuidUtil.get32UUID());
			b = t.save();
		}else{
			b = t.update();
		}
		if(b){
			renderJson(r.ok());
		}else{
			renderJson(r.fail("msg", "保存失败,请稍后再试!"));
		}
	}
}
